package com.wangp.mywrite.s_juc.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @author farling-wangp
 * @version 1.0
 * @date 2020/10/11 15:20
 */
public class AtomicArrayDemo {
    public static void main(String[] args) throws InterruptedException {
        AtomicIntegerArray atomicIntegerArray= new AtomicIntegerArray(1000);
        Incrementer incrementer = new Incrementer(atomicIntegerArray);
        Decrementer decrementer = new Decrementer(atomicIntegerArray);
        Thread[] threadsIncrement = new Thread[100];
        Thread[] threadsDecrement = new Thread[100];
        for (int i = 0; i < 100; i++) {
            threadsIncrement[i] = new Thread(incrementer);
            threadsDecrement[i] = new Thread(decrementer);
            threadsIncrement[i].start();
            threadsDecrement[i].start();
        }
        for (int i = 0; i < 100; i++) {
            threadsDecrement[i].join();
            threadsIncrement[i].join();
        }
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            if(atomicIntegerArray.get(i)!=0){
                System.out.println("发现错误，i="+i);
            }
        }
        System.out.println("运行结束");
    }
}
class Decrementer implements Runnable{

    private AtomicIntegerArray array;

    public Decrementer(AtomicIntegerArray array){
        this.array = array;
    }
    @Override
    public void run() {
        for (int i = 0; i < array.length(); i++) {
            array.getAndDecrement(i);
        }
    }
}

class Incrementer implements Runnable{

    private AtomicIntegerArray array;

    public Incrementer(AtomicIntegerArray array){
        this.array = array;
    }
    @Override
    public void run() {
        for (int i = 0; i < array.length(); i++) {
            array.getAndIncrement(i);
        }
    }
}
